package com.cykj.service.impl;

import com.cykj.mapper.ProjectMapper;
import com.cykj.pojo.CyDetails;
import com.cykj.pojo.CyProject;
import com.cykj.service.ProjectService;
import com.cykj.util.PageResult;
import com.cykj.util.PageUtils;
import com.cykj.util.ResponseDto;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProjectServiceImpl implements ProjectService {
    @Autowired
    private ProjectMapper projectMapper;

    @Override
    public ResponseDto getAllProject(int pageCurr, int pageSize) {
        Page<Object> page = PageHelper.startPage(pageCurr, pageSize);
        List<CyProject> allProject = projectMapper.getAllProject();
        if (allProject != null) {
            PageInfo<Object> pageInfo = new PageInfo<>(page);
            PageResult pageResult = PageUtils.getPageResult(pageInfo);
            return new ResponseDto(1, "项目配置查询成功", pageResult);
        } else {
            return new ResponseDto(0, "查询失败", null);
        }
    }

    @Override
    public ResponseDto changeStatus(int proStatus, int projectId) {

        int i = projectMapper.changeStatus(proStatus, projectId);
        if (i != 0) {
            return new ResponseDto(1, "修改成功", i);
        } else {
            return new ResponseDto(0, "修改失败", null);
        }
    }

    @Override
    public ResponseDto searchProjectInfo(String value, int pageCurr, int pageSize) {
        Page<Object> page = PageHelper.startPage(pageCurr, pageSize);
        List<CyProject> cyProjects = projectMapper.searchProjectInfo(value);
        PageInfo<Object> pageInfo = new PageInfo<>(page);
        PageResult pageResult = PageUtils.getPageResult(pageInfo);
        return new ResponseDto(1, "查询成功", pageResult);
    }

    @Override
    public ResponseDto getAllName() {
        List<String> allName = projectMapper.getAllName();
        return new ResponseDto(1, "查询成功", allName);
    }

    @Transactional(rollbackFor = Exception.class)//如果出现异常了直接回滚
    @Override
    public ResponseDto commitDelete(String checked) {
        //前端将要删除的细项名称变为字符串，再进行分隔
        String[] split = checked.split("，");
        int length = split.length;
        int count = 0;
        try {
            for (int i = 0; i < length; i++){
                int includeProject = projectMapper.selectIsUseName(split[i]);
                if (includeProject != 0 ){
                    return new ResponseDto(-1,"套餐包含该项目，无法删除",null);
                }
            }
            for (int i = 0; i < length; i++) {
                int res = projectMapper.commitDelete(split[i]);
                if (res >= 1) {
                    count++;
                }
            }
            if (count == length) {
                return new ResponseDto(1, "删除成功", null);
            } else {
                return new ResponseDto(0, "删除失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    @Override
    public ResponseDto lookInclude(int id) {
        List<CyDetails> strings = projectMapper.lookInclude(id);
        return new ResponseDto(1, "查看细项", strings);
    }

    @Override
    public ResponseDto addProjectCommit(String name, String fatherDepartId, String price,String details, String status) {
        //查重
        int existPro = projectMapper.isExistPro(name);
        if (existPro != 0){
            return new ResponseDto(0, "该项目已经存在", existPro);
        }
        if (status.equals("2")) {
            status = "0";
        }
        int res = projectMapper.addProjectCommit(
                name, Integer.parseInt(fatherDepartId), Integer.parseInt(price),
                Integer.parseInt(status));
        int projectId = projectMapper.projectIdByName(name);
        System.out.println(details);
        String[] detailsName = details.split(",");
        for (int i = 0; i < detailsName.length; i++) {
            //获取到细项的id
            int detailId = projectMapper.detailsIdByName(detailsName[i]);
            projectMapper.projectAndDetails(projectId,detailId);
        }
        return new ResponseDto(1, "项目插入成功", res);
    }

    @Override
    public ResponseDto alterProject(int projectId, String projectName, String projectPrice, String detailsName) {

        int isAlterProject = 0;
        String msg = (String) getDetailsName(projectId).getData();
        if (!msg.equals(detailsName)) {
            //不相等则说明有修改项目，那就来修改项

            //    获得id和name
            List<Integer> detailsId = DetailsIsExist(detailsName);
            for (int i =0; i<detailsId.size();i++){
                if (detailsId.get(i) == 0 || detailsId.get(i) == -1){
                    return new ResponseDto(-2, "项目修改信息填写有误", null);
                }
            }

            //如果代码能执行到这里就说明要修改的填写没有错误
            //那我们就拿出id和name进行修改
            //那我们就是如果要修改的长度，可能增加，可能减少，那我们怎么办呢？？？ ----》删除记录重新添加
            //删除记录
            projectMapper.deleteDetailsRelative(projectId);
            //添加记录，只需要id
            for (int j = 0; j < detailsId.size(); j++) {
                //    循环插入记录
                //    获取集合里面的每个键值projectId
                projectMapper.addDetailsRelative(projectId, detailsId.get(j));
            }
            //到这里修改项目成功
            isAlterProject = 1;
            //然后就要修改其他的
        }

        CyProject cyProject = projectMapper.searchAlter(projectId, projectName, Integer.parseInt(projectPrice));
        if (cyProject != null && isAlterProject == 0) {
            return new ResponseDto(2, "暂未修改", null);
        } else {
            int i = projectMapper.alterInfo(projectId, projectName, Integer.parseInt(projectPrice));
            if (i != 0) {
                return new ResponseDto(1, "修改成功", null);
            } else {
                return new ResponseDto(0, "修改失败", null);
            }
        }


    }

    public List<Integer> DetailsIsExist(String detailsName) {
        List<Integer> detailsId = new ArrayList<>();
        String[] single = detailsName.split(",");
        //    获得id和name
        for (int i = 0; i < single.length; i++) {
            if (!single[i].contains(":") || single[i].contains("：")) {
                detailsId.clear();
                detailsId.add(-1);//直接添加值为0，返回回去
                return detailsId;
            }
            String[] split = single[i].split(":");//再通过：划分
            //去掉《》获得id和姓名
            int id = Integer.parseInt(split[0].replace("《", ""));
            String name = split[1].replace("》", "");
            System.out.println("id" + id);
            System.out.println(name);
            if (!split[1].contains("》") || !split[0].contains("《")) {
                //如果不包含则说明填写格式有误
                detailsId.clear();
                detailsId.add(-1);//直接添加值为0，返回回去
                return detailsId;
            }
            //查询所填写的id和name是否准确是否匹配
            //循环查询每一个要修改/添加的值是否一致
            int i1 = projectMapper.searchDetails(id, name);
            if (i1 == 0) {
                //如果有一个不存在则说明有一个填写错误，那么就可以直接return
                detailsId.add(0);//直接添加值为0，返回回去
                return detailsId;
            }
            detailsId.add(id);//将id存入集合里面
        }
        return detailsId;
    }

    @Override
    public ResponseDto deleteRow(int projectId) {
        int count = projectMapper.selectIsUse(projectId);
        if (count != 0) {
            //    说明已经被使用
            return new ResponseDto(-1, "改项目已经被套餐包含，无法删除", null);
        }
        int i = projectMapper.deleteRow(projectId);
        if (i != 0) {
            return new ResponseDto(1, "删除成功", null);
        } else {
            return new ResponseDto(0, "删除失败", null);
        }
    }

    //获取细项名字 ---》修改用的
    @Override
    public ResponseDto getDetailsName(int id) {
        List<CyDetails> detailsName = projectMapper.getDetailsName(id);
        String name = "";
        for (int i = 0; i < detailsName.size(); i++) {
            if (i == detailsName.size() - 1) {
                name = name + "《" + detailsName.get(i).getDetailsId() + ":" + detailsName.get(i).getDetailsName() + "》";
            } else {
                name = name + "《" + detailsName.get(i).getDetailsId() + ":" + detailsName.get(i).getDetailsName() + "》,";
            }
        }
        return new ResponseDto(1, "细项名称", name);
    }

    @Override
    public ResponseDto borderPriceSearch(int minPrice, int maxPrice,int pageCurr,int pageSize) {
        Page<Object> page = PageHelper.startPage(pageCurr, pageSize);
        List<CyProject> cyProjects = projectMapper.borderPriceSearch(minPrice, maxPrice);
        if (cyProjects == null){
            return new ResponseDto(0,"查找信息为空",null);
        }else {
            PageInfo<Object> pageInfo = new PageInfo<>(page);
            PageResult pageResult = PageUtils.getPageResult(pageInfo);
            return new ResponseDto(1,"价格区间查找成功",pageResult);
        }
    }

    @Override
    public ResponseDto selectProjectByDetails(String name) {
        List<CyDetails> cyDetails = projectMapper.selectProjectByDetails(name);
        return new ResponseDto(1,"查询成功",cyDetails);
    }

}
